<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>异步Generator函数</title>
</head>
<body>
    <h1>异步Generator函数</h1>

    <script>
        // 基本用法
        async function* asyncGen() {
            yield 'hello';
            yield Promise.resolve('world');
            yield await Promise.resolve('!');
        }

        const ag = asyncGen();
        ag.next().then(({value, done}) => console.log(value)); // 'hello'
        ag.next().then(({value, done}) => console.log(value)); // 'world'
        ag.next().then(({value, done}) => console.log(value)); // '!'

        // 异步Generator实现接口
        class AsyncRange {
            constructor(start, end) {
                this.start = start;
                this.end = end;
            }

            async *[Symbol.asyncIterator]() {
                for (let i = this.start; i <= this.end; i++) {
                    await new Promise(resolve => setTimeout(resolve, 1000));
                    yield i;
                }
            }
        }

        async function useRange() {
            const range = new AsyncRange(1, 3);
            for await (const num of range) {
                console.log(num); // 每隔1秒输出：1, 2, 3
            }
        }

        // 实际应用：异步数据流处理
        async function* streamProcessor(dataStream) {
            for await (const chunk of dataStream) {
                // 数据处理
                const processedData = await processChunk(chunk);
                yield processedData;
            }
        }

        async function processChunk(chunk) {
            // 模拟数据处理
            await new Promise(resolve => setTimeout(resolve, 100));
            return chunk.toUpperCase();
        }

        // 使用数据流处理器
        async function processStream() {
            const dataStream = ['hello', 'world', '!'];
            const processor = streamProcessor(dataStream);

            for await (const data of processor) {
                console.log('处理后的数据:', data);
            }
        }
    </script>
</body>
</html> 